package com.ekuaitu.kuaitu.widget;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.adapter.SearchPositionAdapter;
import com.ekuaitu.kuaitu.base.BaseRcQuickAdapter;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.RecordSQLiteOpenHelper;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Carson_Ho on 16/11/15.
 */
public class SearchPositionView extends LinearLayout implements Inputtips.InputtipsListener, TextWatcher {

    private Context context;
    private List<Tip> mCurrentTipList = new ArrayList<>();
    /*UI组件*/
    private TextView cancelSearch;
    private EditText searchViewSearch;
    private ImageView clearSearch;
    private RelativeLayout loadingSearch;
    /*列表及其适配器*/
    private XRecyclerView rcSearch;
    private SearchPositionAdapter searchAdapter;
    private View footer;
    /*数据库变量*/
    private RecordSQLiteOpenHelper helper;
    private SQLiteDatabase db;
    private FinishActivity mFinishActivity;

    /*三个构造函数*/
    //在构造函数里直接对搜索框进行初始化 - init()
    public SearchPositionView(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SearchPositionView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SearchPositionView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
    }


    /*初始化搜索框*/
    private void init() {
        //实例化数据库SQLiteOpenHelper子类对象
        helper = new RecordSQLiteOpenHelper(context);
        //初始化UI组件
        initView();
    }


    /**
     * 封装的函数
     */

    /*初始化组件*/
    private void initView() {
        LayoutInflater.from(context).inflate(R.layout.search_layout, this);
        searchViewSearch = (EditText) findViewById(R.id.searchView_search);
        searchViewSearch.addTextChangedListener(this);
        cancelSearch = (TextView) findViewById(R.id.cancel_search);
        clearSearch = (ImageView) findViewById(R.id.clear_search);
        rcSearch = (XRecyclerView) findViewById(R.id.rc_search);
        loadingSearch = (RelativeLayout) findViewById(R.id.loading_search);
        //初始化recyclerView
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcSearch.setLayoutManager(linearLayoutManager);
        rcSearch.setItemAnimator(new DefaultItemAnimator());
        rcSearch.setLoadingMoreEnabled(false);
        rcSearch.setPullRefreshEnabled(false);
        footer = LayoutInflater.from(context).inflate(R.layout.footer_search, null);
        footer.findViewById(R.id.header_search).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //清空数据库
                deleteData();
                queryData("");
            }
        });

        //点击取消结束Activity
        cancelSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mFinishActivity.finishActivity();
            }
        });

        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                searchViewSearch.setText("");
                clearSearch.setVisibility(GONE);
            }
        });
        queryData("");

    }


    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        loadingSearch.setVisibility(GONE);
        if (rCode == 1000) {// 正确返回
            mCurrentTipList = tipList;
            searchAdapter = new SearchPositionAdapter(context, R.layout.item_search_position, 1);
            rcSearch.setAdapter(searchAdapter);
            searchAdapter.replaceAll(mCurrentTipList);
            searchAdapter.setOnItemClickListener(new BaseRcQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    insertData(mCurrentTipList.get(position).getName(), mCurrentTipList.get(position).getPoint().getLatitude() + "", mCurrentTipList.get(position).getPoint().getLongitude() + "");
                }
            });
        } else {
            searchAdapter = new SearchPositionAdapter(context, R.layout.item_search_position, 1);
            footer.setVisibility(VISIBLE);
            rcSearch.addFootView(footer);
            rcSearch.setAdapter(searchAdapter);
            searchAdapter.clear();
        }
    }


    /*插入数据*/
    private void insertData(String positionName, String latitude, String longitude) {
        Log.i("sdfsdf", latitude + "  " + longitude);
        if (!hasData(positionName)) {
            db = helper.getWritableDatabase();
            db.execSQL("insert into searchPositionHistory(positionName,latitude,longitude)  values ('" + positionName + "','" + latitude + "','" + longitude + "')");
            db.close();
        }
    }

    /*模糊查询数据 并显示在ListView列表上*/
    private void queryData(String tempName) {
        //模糊搜索
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select * FROM searchPositionHistory where positionName like '%" + tempName + "%' order by id desc ", null);
        List<Map<String, Object>> listQuery = helper.cursorToList(cursor);
        if (listQuery != null && listQuery.size() != 0) {
            Log.i("dfdfd", listQuery.toString());
            mCurrentTipList.clear();
            for (Map map : listQuery) {
                Tip tip = new Tip();
                tip.setName((String) map.get("positionName"));
                tip.setPostion(new LatLonPoint(Double.parseDouble(map.get("latitude").toString()), Double.parseDouble(map.get("longitude").toString())));
                mCurrentTipList.add(tip);
            }
            // 创建adapter适配器对象,装入模糊搜索的结果
            searchAdapter = new SearchPositionAdapter(context, R.layout.item_search_position, 2);
            // 设置适配器
            rcSearch.setAdapter(searchAdapter);
            footer.setVisibility(VISIBLE);
            rcSearch.addFootView(footer);
            searchAdapter.replaceAll(mCurrentTipList);
            searchAdapter.setOnItemClickListener(new BaseRcQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    insertData(mCurrentTipList.get(position).getName(), mCurrentTipList.get(position).getPoint().getLatitude() + "",
                            mCurrentTipList.get(position).getPoint().getLongitude() + "");
                }
            });

        } else {
            searchAdapter = new SearchPositionAdapter(context, R.layout.item_search_position, 2);
            // 设置适配器
            rcSearch.setAdapter(searchAdapter);
            searchAdapter.clear();
            footer.setVisibility(GONE);
            rcSearch.addFootView(footer);
        }


    }

    /*检查数据库中是否已经有该条记录*/
    private boolean hasData(String tempName) {
        //从Record这个表里找到name=tempName的id
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,positionName from searchPositionHistory where positionName =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /*清空数据*/
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from searchPositionHistory");
        db.close();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        footer.setVisibility(GONE);
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (!charSequence.toString().isEmpty()) {
            searchAdapter = new SearchPositionAdapter(context, R.layout.item_search_position, 1);
            // 设置适配器
            rcSearch.setAdapter(searchAdapter);
            searchAdapter.clear();
            loadingSearch.setVisibility(VISIBLE);
            clearSearch.setVisibility(VISIBLE);
            InputtipsQuery inputquery = new InputtipsQuery(charSequence.toString(), Constants.cityName);
            Inputtips inputTips = new Inputtips(context, inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        } else {
            clearSearch.setVisibility(GONE);
            queryData("");
        }

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }


    public interface FinishActivity {
        public void finishActivity();
    }

    public void setFinishActivity(FinishActivity finishActivity) {
        mFinishActivity = finishActivity;
    }


}

